﻿var access_token;
var prev_access_token, cur_access_token;
window.FB = FBWinJS;
var share = false;
var myFriends = null;
var playCheck = false;

/*Enter your app-id from facebook for your app here.*/
FB.options({
    appId: 'xxxxxxxxxxxxxxxxxxx'
});

//Your mobile service authentication goes here
// http://go.microsoft.com/fwlink/?LinkID=290993&clcid=0x409
var mobileserviceauthentClient = new WindowsAzure.MobileServiceClient(
                YOUR_MOBILE_SERVICE_URL,
                YOUR_MOBILE_SERVICE_SECRET);

// Defined the todoItems list used for data binding.
var Items = new WinJS.Binding.List();

var azure_userInfoTable = mobileserviceauthentClient.getTable('TABLE_NAME_IN_YOUR_MOBILE_SERVICE'); //Enter table name here

(function () {
    "use strict";
    var currentApp = Windows.ApplicationModel.Store.CurrentAppSimulator;
    var page = WinJS.UI.Pages.define("/html/trialExtension.html", {
        ready: function (element, options) {
            /*The code in ready function goes into the block of your app.load() function */
            createDB();
            // Initialize the license proxy file
            loadTrialModeProxyFile();
            //load userinfo data into local data from azure mobile services table
            loadFromAzureToLocalDb();
            document.getElementById("trialTime").addEventListener("click", caculateTrialTime, false);
            document.getElementById("Login").addEventListener("click", shareProduct2, false);
            document.getElementById("trialProduct").addEventListener("click", runTrialProduct, false);
            document.getElementById("fullProduct").addEventListener("click", runFullProduct, false);
            document.getElementById("convertTrial").addEventListener("click", doTrialConversion, false);
            document.getElementById("TotalShares").addEventListener("click", getTotalShares, false);
            document.getElementById("Share").addEventListener("click", shareExtendTrial, false);
            document.getElementById("reset").addEventListener("click", resetAccountInfo, false);
        },
        unload: function () {
            /*The code in unload function goes into the block of your app.unload() function */
            currentApp.licenseInformation.removeEventListener("licensechanged", trialModeRefreshScenario);
        }
    });

    function loadTrialModeProxyFile() {
        Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync("data").done(
            function (folder) {
                folder.getFileAsync("trial-mode.xml").done(
                    function (file) {
                        currentApp.licenseInformation.addEventListener("licensechanged", trialModeRefreshScenario);
                        Windows.ApplicationModel.Store.CurrentAppSimulator.reloadSimulatorAsync(file).done();
                    });
            });
    }    

    function resetAccountInfo() {
        if (access_token) {
            resetClicked();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        resetClicked();
                    }
                }
            });
        }
        function resetClicked() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
                //gettinng userInfo from the userInfo table in the AppDB database                
                indexedDataBaseOp(searchAndDelData, response);
                displayCurrentLicenseMode();
            });
        }
    }

    function shareExtendTrial() {

        if (access_token) {
            shareClicked();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {

                        access_token = result.access_token;
                        shareClicked();
                    }
                }
            });
        }


        function shareClicked() {
            FB.setAccessToken(access_token);

            var body = 'I like this app';
            FB.api('me/feed', 'post', {
                message: body, link: "", caption: "Lets Play TicTac", name: "TicTac", picture: "http://ts2.mm.bing.net/th?id=H.4528524587173721&w=194&h=184&c=7&rs=1&pid=1.7"
            }, function (response) {
                if (!response || response.error) {
                    console.log(!response ? 'error occurred' : response.error);
                    WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
                    return;
                }
                else {
                    share = true;
                    WinJS.log && WinJS.log("Thank You for sharing about the app", "sample", "error");
                }
                console.log('Post Id: ' + response.id);
                var ids = response.id.split("_");
                if (share === true) {

                    indexedDataBaseOp(searchData, ids);
                    share = false;
                }
                else {
                    WinJS.log && WinJS.log("Unable to extend trial, share failed.", "sample", "error");
                }
            });
        }
    }
    //shareExtendTrial ends here

    function getTotalShares() {

        if (access_token) {
            getUserShareInfo();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {

                        access_token = result.access_token;
                        getUserShareInfo();
                    }
                }
            });
        }

        function getUserShareInfo() {

            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
                //gettinng userInfo from the userInfo table in the AppDB database
                indexedDataBaseOp(searchDataForShares, response);
            });
        }
    }
    //end of getTotalShares

    //start of buying the app
    function doTrialConversion() {
        WinJS.log && WinJS.log("Buying the full license...", "sample", "status");
        if (access_token) {
            getUserLicenseInfoForBuy();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        getUserLicenseInfoForBuy();
                    }
                }
            });
        }
        function getUserLicenseInfoForBuy() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
               
                indexedDataBaseOp(searchDataUserLicenseInfo, response, currentApp);                
            });
        }
    }
    //end of doTrialConversion

    function runTrialProduct() {
        if (access_token) {
            getUserLicenseInfo1();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        getUserLicenseInfo1();
                    }
                }
            });
        }
        function getUserLicenseInfo1() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
                //gettinng userInfo from the userInfo table in the AppDB database               
                    indexedDataBaseOp(searchDataForTrialInfo,response );                
            });
        }
    }
    //end of runTrialProduct

    function runFullProduct() {
        if (access_token) {
            getUserLicenseInfo1();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        getUserLicenseInfo1();
                    }
                }
            });
        }
        function getUserLicenseInfo1() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);                
                indexedDataBaseOp(searchDataFullLicenseInfo, response);
           });
        }
    }
    //end of runFullProduct

    function trialModeRefreshScenario() {
        // setup application upsell message
        currentApp.loadListingInformationAsync().done(
        function (listing) {
            document.getElementById("purchasePrice").innerText = "You can buy the full app for: " + listing.formattedPrice + ".";
        },
        function () {
            WinJS.log && WinJS.log("LoadListingInformationAsync API call failed", "sample", "error");
        });
        displayCurrentLicenseMode();
    }

    function displayCurrentLicenseMode() {
        if (access_token) {
            getUserLicenseInfo();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        getUserLicenseInfo();
                    }
                }
            });
        }
        function getUserLicenseInfo() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
                //gettinng userInfo from the userInfo table in the AppDB database
                indexedDataBaseOp(searchDataForLicenseChange, response);               
            });
        }
    }
    
    function caculateTrialTime() {
        if (access_token) {
            getUserInfo();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        getUserInfo();
                    }
                }
            });
        }
        function getUserInfo() {
            FB.api('/me',
            { fields: "name,first_name,picture" },
            function (response) {
                logResponse(response);
                //gettinng userInfo from the userInfo table in the AppDB database
                indexedDataBaseOp(searchDataTrialTimeRemaining, response);               
            });
        }
    }
    
    // For logging responses
    function logResponse(response) {
        if (typeof console !== 'undefined')
            console.log('The response was', response);
    }

    // AUTHENTICATION
    function loginClicked() {
        if (access_token) {
            updateUserInfo();
        }
        else {
            askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                if (error) {
                    console.log(error);
                    return;
                } else {
                    if (result.access_token) {
                        access_token = result.access_token;
                        updateUserInfo();
                    }
                }
            });
        }
    }

    function postClicked() {
        FB.setAccessToken(access_token);
        var body = 'I like this app';
        FB.api('me/feed', 'post', {
            message: body, link: "", caption: "Social Promotional Video", name: "TicTac", source: "http://ie.microsoft.com/testdrive/Videos/BehindIE9AllAroundFast/Video.mp4", type: 'video'
        }, function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
                return;
            }
            console.log('Post Id: ' + res.id);
            WinJS.log && WinJS.log("Thank You for sharing the promo video.", "sample", "error");
            share = true;

            if (share === true && cur_access_token == prev_access_token) {
                var a = document.getElementById("points").innerText;
                var b = parseInt(a);
                b = b + 50;
                document.getElementById("points").innerText = b;
                share = false;
            }
            else {
                WinJS.log && WinJS.log("Unable to update points, share failed.", "sample", "error");
            }
        });
    }

    function askForPermissions(scope, callback) {
        var redirectUri = 'https://www.facebook.com/connect/login_success.html',
            loginUrl = FB.getLoginUrl({ scope: scope });
        try {
            Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
                Windows.Security.Authentication.Web.WebAuthenticationBroker.default,
                new Windows.Foundation.Uri(loginUrl),
                new Windows.Foundation.Uri(redirectUri))
                .then(function success(result) {
                    if (result.responseStatus == 2) {
                        console.log('error: ' + result.responseerrordetail);
                        callback(new Error(result.responseerrordetail));
                        return;
                    }
                    var parser = document.createElement('a');
                    parser.href = result.responseData;

                    var qs = extractQuerystring(parser.hash.substr(1).split('&'));

                    if (qs.error) {
                        // most likely user clicked don't allow
                        console.log('error: ' + qs.error + ' : ' + qs.error_description);
                        return;
                    }
                    // set it as the default access token.
                    FB.setAccessToken(qs.access_token);
                    callback(null, qs);

                }, function error(err) {
                    console.log('Error Number: ' + err.number);
                    console.log('Error Message: ' + err.message);
                    callback(new Error(err.message));
                });
        } catch (e) {
            // error launching web auth
            console.log(e);
        }
    }

    function extractQuerystring(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    }

    function updateUserInfo(response) {
        FB.api('/me',
          { fields: "name,first_name,picture" },
          function (response) {
              logResponse(response);
              //adding info to userInfo table in the AppDB database
              indexedDataBaseOp(addData, response);              
          });
    }

    function shareProduct2() {
        loginClicked();
    }
})();

